#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QNetworkInterface>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 初始化UI
    setWindowTitle("网关搜索工具");
    ui->logText->setReadOnly(true);
    ui->pushButton->setEnabled(false);

    // 创建UDP套接字
    udpSocket = new QUdpSocket(this);
    if (!udpSocket->bind(QHostAddress::AnyIPv4, 0, QUdpSocket::ShareAddress)) {
        logMessage("绑定UDP端口失败: " + udpSocket->errorString());
        QMessageBox::critical(this, "错误", "无法绑定UDP端口，请检查网络连接");
    }

    // 设置定时器
    searchTimer = new QTimer(this);
    searchTimer->setSingleShot(true);
    searchTimer->setInterval(5000); // 5秒超时

    // 连接信号槽
    connect(udpSocket, &QUdpSocket::readyRead, this, &MainWindow::readPendingDatagrams);
    connect(searchTimer, &QTimer::timeout, this, &MainWindow::handleTimeout);
    connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(changeScreen()));
    //xiesi
    connect(ui->pushButton_2, SIGNAL(clicked()), this, SLOT(myslot()));

    logMessage("应用程序已启动，准备搜索网关...");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_searchButton_clicked()
{
    ui->searchButton->setEnabled(false);
    ui->logText->clear();
    logMessage("开始搜索网关...");

    sendBroadcast();
    searchTimer->start();
}

void MainWindow::sendBroadcast()
{
    // 构造请求JSON
    QJsonObject request;
    request["type"] = 0;
    request["request"] = "connect_info";

    QJsonDocument doc(request);
    QByteArray datagram = doc.toJson(QJsonDocument::Compact);

    // 发送广播到所有网络接口
    const QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
    bool broadcastSent = false;

    for (const QNetworkInterface &interface : interfaces) {
        if ((interface.flags() & QNetworkInterface::IsUp) &&
                (interface.flags() & QNetworkInterface::CanBroadcast) &&
                !(interface.flags() & QNetworkInterface::IsLoopBack)) {

            const QList<QNetworkAddressEntry> entries = interface.addressEntries();
            for (const QNetworkAddressEntry &entry : entries) {
                QHostAddress broadcastAddress = entry.broadcast();
                if (broadcastAddress != QHostAddress::Null && entry.ip().protocol() == QAbstractSocket::IPv4Protocol) {
                    // 发送到网关的UDP端口（根据实际情况修改端口号）
                    qint64 sent = udpSocket->writeDatagram(datagram, broadcastAddress, 8880);
                    if (sent == -1) {
                        logMessage("广播发送失败 (" + interface.name() + "): " + udpSocket->errorString());
                    } else {
                        logMessage("广播已发送到 " + broadcastAddress.toString());
                        broadcastSent = true;
                    }
                }
            }
        }
    }

    if (!broadcastSent) {
        logMessage("未找到支持广播的网络接口!");
        ui->searchButton->setEnabled(true);
        searchTimer->stop();
    }
}
void MainWindow::readPendingDatagrams()
{
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

        // 尝试多种解析方法
        QJsonParseError error;

        // 转换为字符串后解析
        QString jsonStr = QString::fromUtf8(datagram);
        QJsonDocument doc2 = QJsonDocument::fromJson(jsonStr.toUtf8(), &error);

        if (doc2.isObject()) {
            processGatewayResponse(doc2.object(), sender);
        }
        else {
            logMessage("所有解析方法都失败 (" + sender.toString() + ")");
        }
    }
}

void MainWindow::processGatewayResponse(const QJsonObject &json, const QHostAddress &sender)
{
    if (json["type"].toInt() == 0 && json.contains("data")) {
        searchTimer->stop(); // 停止超时计时器

        QJsonObject data = json["data"].toObject();
        QString tcpAddress = data["tcp_address"].toString();
        QString tcpPort = data["tcp_port"].toString();

        logMessage("\n=== 发现网关 ===");
        logMessage("IP地址: " + sender.toString());
        logMessage("tcp地址: " + tcpAddress);
        logMessage("tcp端口: " + tcpPort);

        // 更新UI显示
        ui->ipLabel->setText("IP: " + sender.toString());
        ui->mqttLabel->setText("PORT: " + tcpPort);
        qDebug() << sender.toString() << tcpPort;
        mainwindow1->setNetworkInfo(sender.toString(), tcpPort);
        ui->searchButton->setEnabled(true);
        ui->pushButton->setEnabled(true);
    } else {
        logMessage("收到无效网关响应 (" + sender.toString() + ")");
    }
}

void MainWindow::handleTimeout()
{
    logMessage("\n搜索超时，未发现网关设备");
    ui->searchButton->setEnabled(true);
}

void MainWindow::changeScreen()
{
    mainwindow1->show();
    this->close();
}

void MainWindow::myslot()
{
    mainwindow1->show();
    this->close();
}

void MainWindow::logMessage(const QString &message)
{
    ui->logText->append(message);
}
